package cn.jhc.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.User;
import cn.jhc.db.DbFactory;

/**
 * Servlet implementation class LoginServet
 */
@WebServlet("/login.do")
public class LoginServet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServet() {
        super();
        // TODO Auto-generated constructor stub
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = null;
		try {
			user = DbFactory.getUserDao().login(username, password);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new IOException(e);
		}
		if (user != null) {
			request.getSession().setAttribute("currentUser", user);
			response.sendRedirect("./user/first.jsp");
		} else {
			response.sendRedirect("./failed.jsp");
		}
	}

}
